//
//  YYAlamofireExtension.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/8/10.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import Alamofire

extension YYAlamofire {
    
    static func sign(params: [String: String]) -> [String: String] {
        var dic = params
        dic["api_version"] = api_version
        
        let dic2 = dic.sorted { $0.0 < $1.0 }
        
        var signString = ""
        var firstKey = true
        for (key, value) in dic2 {
            if firstKey {
                signString  = "\(signString)\(key)=\(value)"
                firstKey = false
            } else {
                signString  = "\(signString)&\(key)=\(value)"
            }
        }
        signString = "\(signString)\(appSecret)"
        yy_Log("签名字符串：\(signString)")
        
        dic["sign"] = signString.md5()
        
        return dic
    }
    
    static func analyzResponseData(value: Any?, url: String = "unkown interface") -> (success: Bool, data: Any?) {
        let data =  value as? [String: Any]
        
        if let data = data {
            let success = data["success"] as? Bool ?? false
            if success {
                if JSONSerialization.isValidJSONObject(data) {
                    let jsonData = try! JSONSerialization.data(withJSONObject: data, options: [])
                    yy_LogInfo(String(data: jsonData, encoding: .utf8)!)
                }
                return (true, data["data"])
            } else {
                let urlArr = url.components(separatedBy: "?")
                let userInfo = ["params": urlArr.last ?? "", "data": data] as [String : Any]
                yy_reportError(domain: (urlArr.first ?? "unkown interface") + ", errmsg: " + (data["message"] as? String ?? ""), code: 0, userInfo: userInfo)
                return (false, data["message"])
            }
        } else {
            return (false, nil)
        }
    }
    
}
